import React, { useEffect, useState, useRef } from 'react';
import axios from 'axios';
import { useLocation, useNavigate } from 'react-router-dom';
import data from '@emoji-mart/data'
import Picker from '@emoji-mart/react'
import '../css/Chat.css';
import { NavBar, ImageUploader, ImageViewer, PullToRefresh } from 'antd-mobile';
import { Sticky } from 'react-vant'
import { PictureOutline } from 'antd-mobile-icons';
import { sleep } from 'antd-mobile/es/utils/sleep'
// import { useSpeechRecognition } from 'react-speech-recognition';
// import SpeechToText from './SpeechToText';
axios.defaults.baseURL = 'http://127.0.0.1:3000';
const Chat = () => {
    const navigate = useNavigate();
    // 返回上一页
    const back = () => navigate(-1);

    const [messages, setMessages] = useState([]);// 所有的消息
    const [input, setInput] = useState('');// 输入的信息
    const [imgUrl, setImgUrl] = useState(''); // 发送图片的路径
    const wsRef = useRef(null); // websocket连接的实例
    const { state: { userId, recipientId } } = useLocation();

    const [stores, setStores] = useState({}); //商家信息
    const [userInfo, setUserInfo] = useState({}); //用户信息

    const [showEmoji, setShowEmoji] = useState(false); //emoji是否展示
    const [showMore, setShowMore] = useState(false); //更多功能是否展示

    const [isInput, setIsInput] = useState(false);//是否准备发送消息

    const msgRef = useRef(null); //消息div

    const [visible, setVisible] = useState(false) //图片预览显示
    const [imgsrc, setImgSrc] = useState(''); //预览图片的路径

    const [isViewHistory, setIsViewHistory] = useState(false);
    const pageSize = 10;
    const [page, setPage] = useState(1);
    const [sumPage, setSumPage] = useState(0);

    // 获取联系的商家
    const storeInfo = async () => {
        const { data: { code, data } } = await axios.get('/message/storeInfo', { params: { id: recipientId } });
        if (code === 200) {
            setStores(data);
        }
    }
    // 获取用户信息
    const getUserInfo = async () => {
        const { data: { code, data } } = await axios.get('/message/userInfo', { params: { id: userId } });
        if (code === 200) {
            setUserInfo(data);
        }
    }
    // 设置心跳间隔时间
    const HEARTBEAT_INTERVAL = 60000;
    let heartbeatInterval; //心跳机制计时器

    // 心跳函数
    const heartbeat = () => {
        if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
            wsRef.current.send(JSON.stringify({ recipientId, content: 'ping', type: 'text' }));// 发送心跳消息
        }
    };

    // 重置心跳函数
    const resetHeartbeat = () => {
        clearInterval(heartbeatInterval); // 清除旧的心跳定时器
        heartbeatInterval = setInterval(heartbeat, HEARTBEAT_INTERVAL); // 设置新的心跳定时器
    };
    // WebSocket连接函数
    const initWebSocket = () => {
        console.log(recipientId);

        // 建立WebSocket连接  
        wsRef.current = new WebSocket(`ws://localhost:8000?userId=${encodeURIComponent(userId)}`);
        wsRef.current.onopen = () => {
            console.log('Connected to WebSocket server');
            resetHeartbeat(); // 连接成功后重置心跳
        };

        wsRef.current.onmessage = (event) => {
            const { senderId, content, type } = JSON.parse(event.data);
            if (content === 'pong') {
                resetHeartbeat(); // 收到服务器响应后重置心跳
            } else {
                setMessages((prevMessages) => [...prevMessages, { senderId, content, type }]);
                scrollBottom();
            }
        };

        wsRef.current.onclose = () => {
            console.log('Disconnected from WebSocket server');
            // 重新连接的逻辑  
            // setTimeout(initWebSocket, 5000);
        };

        wsRef.current.onerror = (error) => {
            console.error('WebSocket error:', error);
            // 通知用户或尝试重新连接  
        };

    }
    useEffect(() => {
        // 清理函数，确保在组件卸载时关闭WebSocket连接  
        const cleanup = () => {
            console.log('关闭');
            clearInterval(heartbeatInterval)
            if (wsRef.current) {
                wsRef.current.close();
            }
        };
        // 初始化连接
        initWebSocket();
        storeInfo(); //商家信息
        getUserInfo(); // 用户信息

        // 组件卸载时清理  
        return cleanup;
    }, [userId, recipientId]); // 注意：依赖项确保在userId或recipientId变化时重新连接  

    useEffect(() => {
        getMessage(); //获取聊天记录
    }, [page])
    // 获取历史聊天内容
    const getMessage = async () => {
        const { data: { data, code, sumPage } } = await axios.get('/message/message', { params: { userId, recipientId, page, pageSize } });
        if (code === 200) {
            setMessages((prevMessages) => [...data, ...prevMessages]);
            setSumPage(sumPage)
        }
    }

    // 发送消息
    const sendMessage = (message, type) => {
        if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
            wsRef.current.send(JSON.stringify({ recipientId, content: message, type }));
        }
    };
    // 点击发送按钮
    const handleSend = () => {
        if (input) {
            sendMessage(input, 'text');
            setInput('');
        }
        if (imgUrl) {
            sendMessage(imgUrl, 'image');
            setImgUrl('');
            setShowMore(false);
            setIsInput(false);
        }

    };

    // 处理图片
    const handleFileChange = async (file) => {
        const formData = new FormData();
        formData.append('image', file);
        try {
            const response = await axios.post('/message/imgUpload', formData);
            setImgUrl(response.data.url)
            return {
                url: URL.createObjectURL(file),
            }
        } catch (error) {
            console.error('Error uploading image:', error);
        }
    };


    useEffect(() => {
        if (isViewHistory) return;
        scrollBottom();
    }, [isInput, messages])
    // 消息滚动到顶部
    const scrollBottom = () => {
        if (msgRef.current) {
            msgRef.current.scrollTo({
                top: msgRef.current.scrollHeight,
                behavior: 'smooth'
            });
        }
    }


    // 点击emoji表情
    const handleEmojiClick = (emoji) => {
        setInput(input + emoji.native);
    }
    // 控制emoji的显示
    const emoji = () => {
        setShowEmoji(true);
        setShowMore(false);
        setIsInput(true);
        setIsViewHistory(false);
    }

    // 更多功能的显示
    const more = () => {
        setShowMore(true);
        setShowEmoji(false);
        setIsInput(true);
        setIsViewHistory(false);

    }
    // 点击聊天页面输入框收回
    const resetMsg = () => {
        setIsInput(false);
        setShowMore(false);
        setShowEmoji(false);
        
    }


    // 图片预览
    const showImg = (e) => {
        setVisible(true);
        setImgSrc(e.target.src)
    }

    const statusRecord = {
        pulling: '用力拉',
        canRelease: '松开吧',
        refreshing: '玩命加载中...',
        complete: '好啦',
    }
    return (
        <div className='chatPage'>
            <Sticky>
                <div className='charPage-top'>
                    <NavBar onBack={back}>{stores.shop}</NavBar>
                </div>
            </Sticky>
            <div ref={msgRef} className='msg' onClick={() => resetMsg()} style={{ height: isInput ? "calc(100vh - 7rem)" : "calc(100vh - 2rem)" }}>
                <PullToRefresh
                    onRefresh={async () => {
                        await sleep(1000);
                        setIsViewHistory(true);
                        if (page == sumPage + 1) {
                            setPage(sumPage + 1)
                        } else {
                            setPage((cur) => cur + 1)
                        }
                    }}
                    renderText={status => {
                        return <div>{statusRecord[status]}</div>
                    }}
                >
                    {messages.map((msg, index) => (
                        msg.senderId == userId ?
                            <div className='chatMsg' key={msg._id || index} style={{ textAlign: msg.senderId == userId ? 'right' : 'left' }}>
                                {
                                    msg.type == 'image' ?
                                        <img src={msg.content} onClick={(e) => showImg(e)} alt="" style={{ width: "100px", height: "100px" }} />
                                        :
                                        <span className='chatText'>{msg.content}</span>
                                }
                                <img src={userInfo.picture} alt="" style={{ marginLeft: "0.1rem" }} />

                            </div>
                            :
                            <div className='chatMsg' key={msg._id || index} style={{ textAlign: msg.senderId == userId ? 'right' : 'left' }}>
                                <img src={stores.src} alt="" style={{ marginRight: "0.1rem",borderRadius:"50%" }} />
                                {
                                    msg.type == 'image' ?
                                        <img src={msg.content} onClick={(e) => showImg(e)} alt="" style={{ width: "100px", height: "100px" }} />
                                        :
                                        <span className='chatText'>{msg.content}</span>
                                }
                            </div>
                    ))}
                </PullToRefresh>
                <ImageViewer
                    classNames={{
                        mask: 'customize-mask',
                        body: 'customize-body',
                    }}
                    image={imgsrc}
                    visible={visible}
                    onClose={() => {
                        setVisible(false)
                    }}
                />
            </div>

            <div className='sendMessage'>
                <input type="text"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    placeholder="Send a message"
                    aria-label="Chat input"
                    onFocus={() => { scrollBottom(); setIsViewHistory(false) }}
                    style={{ width: input.length > 0 ? "4.5rem" : "6rem" }}
                />
                <div style={{ width: "0.6rem", height: "0.6rem", textAlign: 'center' }} onClick={() => emoji()}>
                    <svg className="icon" aria-hidden="true">
                        <use xlinkHref="#icon-emoji" ></use>
                    </svg>
                </div>
                <div style={{ width: "0.6rem", height: "0.6rem", textAlign: 'center' }} onClick={() => more()}>
                    <svg className="icon" aria-hidden="true">
                        <use xlinkHref="#icon-27CIRCLE" ></use>
                    </svg>
                </div>
                {
                    (input.length > 0 || imgUrl.length > 0) && <button className='sendBtn' onClick={() => handleSend()}>发送</button>
                }
            </div>

            {/* <SpeechToText /> */}
            {/* emoji表情包 */}
            <div style={{ width: "100vw", maxHeight: "5rem", overflow: "hidden" }}>
                {
                    showEmoji && <Picker
                        data={data}
                        onEmojiSelect={handleEmojiClick}
                        searchPosition="none"
                        previewPosition="none"
                        emojiButtonSize={38}
                        emojiSize={30}
                    />
                }
                {
                    showMore && <div>
                        <div className='moreItem'>
                            <ImageUploader upload={handleFileChange} >
                                <PictureOutline fontSize="1.2rem" />
                            </ImageUploader>
                            <p>图片</p>
                        </div>
                    </div>
                }

            </div>

        </div>
    );
};

export default Chat;